//
//  WalletViewController.m
//  HaoDeCaiFu
//
//  Created by 物联信息中心 on 2018/1/2.
//  Copyright © 2018年 郑开宏. All rights reserved.
//

#import "WalletViewController.h"
#import "ChongzhiViewController.h"
#import "jiaoyiMingxiTableViewController.h"
#import "ShouyiMingxiTableViewController.h"
#import "QuxianViewController.h"
#import <WebKit/WebKit.h>
#import "GeneralMagager.h"
@interface WalletViewController ()<WKUIDelegate, WKNavigationDelegate>
@property (nonatomic, weak) WKWebView *webView;
@property(nonatomic,strong)NSMutableArray*xArray;
@property(nonatomic,strong)NSMutableArray*yArray;

@end

@implementation WalletViewController

-(void)viewWillAppear:(BOOL)animated
{
     self.navigationController.navigationBarHidden=YES;
}
-(void)viewDidDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.xArray=[NSMutableArray array];
    self.yArray=[NSMutableArray array];
    self.lineView.backgroundColor=ZKcolor(240, 240, 240);
    self.bgColorView.backgroundColor=ZKcolor(240, 240, 240);
    
    self.walletNumLalbe.text=[NSString stringWithFormat:@"%.2f",[self.walletDic[@"totalCurrentValue"] floatValue]];
    self.yesterDayLable.text=[NSString stringWithFormat:@"%.2f",[self.walletDic[@"preProfitLoss"] floatValue]];
    //    vc.walletNumLalbe.text=[NSString stringWithFormat:@"%.2f",[self.walletDic[@"totalCurrentValue"] floatValue]];
    self.leijiLable.text=[NSString stringWithFormat:@"%.2f",[self.walletDic[@"profitLoss"] floatValue]];
    [self getMyWalltWanfenShouyi];
    [self getMyWalltJijinShouyi];
    
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    CGRect rect = CGRectMake(0, 30, screenWidth, 165);
    WKWebView *webview = [[WKWebView alloc] initWithFrame:rect configuration:config];
    webview.navigationDelegate = self;
    webview.scrollView.scrollEnabled = NO;
    webview.UIDelegate = self;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"echarts" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:path];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];
    [self.zhexianTuView addSubview:webview];
    _webView = webview;
    
    
    // Do any additional setup after loading the view from its nib.
}


- (void)getMyWalltWanfenShouyi{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"startDate"] = [self getOneMonthAgo];
     paramets[@"endDate"] = [self getTodayDate];
     paramets[@"pageSize"] = @"30";
     paramets[@"pageIndex"] = @"1";
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:@"/public/wallet/find-cash-wallet-fund-history-nav"};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
       
        if ([code isEqualToString:@"0000"]) {
            NSArray*bigDataArray=[result objectForKey:@"data"];
            if (bigDataArray.count!=0) {
                NSDictionary*dataDic=bigDataArray[0];
                NSArray*smallDataArray=[dataDic objectForKey:@"data"];
                for (NSDictionary*dic in smallDataArray) {
                    [self.xArray addObject:[GeneralMagager shijianChuoZhuanshijianWith:[dic objectForKey:@"navDate"]]];
                    [self.yArray addObject:[NSString stringWithFormat:@"%f",[[dic objectForKey:@"earningsPer10000"] doubleValue]]];
                }
                [_webView reload];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
    
}

- (void)getMyWalltJijinShouyi{
   
    
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"startDate"] = [self getOneMonthAgo];
    paramets[@"endDate"] = [self getTodayDate];
    paramets[@"pageSize"] = @"30";
    paramets[@"pageIndex"] = @"1";
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:@"/public/wallet/find-cash-wallet-fund-basic-info"};
    
    LSWeakSelf;
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        
        if ([code isEqualToString:@"0000"]) {
            NSArray*bigDataArray=[result objectForKey:@"data"];
            if (bigDataArray.count!=0) {
                NSDictionary*dataDic=bigDataArray[0];
                
                weakSelf.sevenYearLable.text=[NSString stringWithFormat:@"七日年化：%.4f%%",[[dataDic objectForKey:@"sevenDaysAnnualizedYield"] floatValue]];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
    
}

-(NSString*)getOneMonthAgo
{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    //    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期，month day 类推
    [lastMonthComps setMonth:-1];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *dateStr = [formatter stringFromDate:newdate];
    return dateStr;
    
    

}

-(NSString*)getTodayDate
{
    NSDateFormatter*formartter=[[NSDateFormatter alloc]init];
    [formartter setDateFormat:@"YYYY-MM-DD"];
    NSString*dateStr=[formartter stringFromDate:[NSDate date]];
    return dateStr;
}


- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}

-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    NSMutableDictionary *htmlDict = [NSMutableDictionary dictionary];
   
    htmlDict[@"xData"] = self.xArray;
    htmlDict[@"yData"] =[NSMutableArray arrayWithObject:self.yArray];
    htmlDict[@"legend"] = [NSArray arrayWithObjects:@"组合收益(%)", nil];
    NSString *str = [self dictionaryToJson:htmlDict];
    NSString *finalStr = [NSString stringWithFormat:@"initChart(%@)", str];
    [self.webView evaluateJavaScript:finalStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        //TODO
        
        NSLog(@"%@___%@",error,error.localizedDescription);
        
    }];
    
}





- (IBAction)backBtnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)mingxiBtnClick:(UIButton *)sender {
    
    jiaoyiMingxiTableViewController*vc=[[jiaoyiMingxiTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)quxianBtnClick:(UIButton *)sender {
    
    QuxianViewController*vc=[[QuxianViewController alloc]init];
    NSLog(@"%@",self.walletDic);
    vc.availableValue=self.walletDic[@"availableValue"];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)chongzhiBtnClick:(UIButton *)sender {
    
    ChongzhiViewController*vc=[[ChongzhiViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)shouyiMingxiEnterBtnClick:(UIButton *)sender {
    
    ShouyiMingxiTableViewController*vc=[[ShouyiMingxiTableViewController alloc]init];
    vc.leijiShouyi=[NSString stringWithFormat:@"%.2f",[self.walletDic[@"profitLoss"] floatValue]];
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
